import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
const VIP = { template: '<div>我是嵌套视图VIP</div>' }
const viewNamed = { template: '<div>默认视图</div>' }
const viewNamedA = { template: '<div>视图A</div>' }
const viewNamedB = { template: '<div>视图B</div>' }
const router = new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: () => import('@/pages/index')
    },
    // 命名视图
    {
      path: '/viewNamed',
      name: 'viewNamed',
      components: {
        default: viewNamed,
        a: viewNamedA,
        b: viewNamedB
      }
    },
    // 动态路由
    {
      path: '/user/:id',
      name: 'user',
      component: () => import('@/components/User'),
      children: [{ path: 'vip', component: VIP }]
    },
    {
      path: '/movieList',
      name: 'movieList',
      component: () => import('@/pages/moviesList'),
      meta: {
        title: '电影列表'
      }
    },
    {
      path: '/loginPage',
      name: 'loginPage',
      component: () => import('@/pages/loginPage'),
      meta: {
        title: '登录'
      }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/pages/registerPage'),
      meta: {
        title: '注册'
      }
    },
    {
      path: '/findPassword',
      name: 'findPassword',
      component: () => import('@/pages/findPasswordPage'),
      meta: {
        title: '找回密码'
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    let auth = {}
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router
